/**初始化分页条数集合*/
var pageList=[5, 10, 25, 50, 100];

$X().conf({ url: ecp_boss_server + '/openx', type: 'app' });
$.extend({
    openx: {
        tableId: '#table',
        rows: [],
        url: ecp_boss_server,
        pageNumber:1, // 默认为第一页
        pageSize:10,
        /**表格工具条上的增删改成按钮，执行时需要重写*/
        insert: function () {
        },
        update: function () {
        },
        delete: function () {
        },
        query: function () {
        },
        /**统一确认框样式*/
        confirm: function (tips, callback) {
            layer.confirm(tips, { icon: 3, title: '提示' }, function (index) {
                if (callback) {
                    callback(index);
                }
            });
        },
        /** 弹出框 area = null ,divId 层ID 将进行自适应
         *  使用方式 area = null   宽高进行自适应   area = ['',''500px]   宽度进行自适应 。
         *  title： 显示标题
         *  content： 显示的DIV 内容
         *  shadeClose ： 点击弹出层其他地方 弹出层是否消失
         *  callback : 点击弹出层中的确定按钮进行回调
         * */
        openLayer: function (area, title, content, shadeClose, callback) {
            var h = 'auto';
            var w = 'auto';
            /**高度自适应处理*/
            if (!area || !area[1]) {
                var div = $("<div id='bussTplDiv'></div>").attr("id", "_bussTplDiv").css("display", "none")
                $(div).appendTo('body')
                $(content).appendTo("#_bussTplDiv");
                h = $("#_bussTplDiv").height() + 80;
                w =$("#_bussTplDiv").width() + 60
                if (h > $(window).height()) {
                    h = $(window).height() - 60;
                }

                if (w > $(window).width()) {
                    w = $(window).width() - 60;
                }

                $("#_bussTplDiv").remove();
                h = h + 'px'
                w = w + 'px'
            }

            if (area && area[0] && area[0] != 'auto') {
                w = area[0] + 'px';
            }
            if (area && area[1] && area[1] != 'auto') {
                h = area[1] + 'px';
            }

            console.log("宽度：" + w + " 高度：" + h)

            var index = layer.open({
                type: 1,
                area: [w, h],
                shadeClose: (shadeClose == undefined || shadeClose) ? true : false, // 点击遮罩关闭
                maxmin: true,
                moveOut: false,
                scrollbar: true,
                title: !title ? '操作' : '<b>' + title + '</b>',
                content: content,
                shift: 1,
                btn: callback ? ['确定', '取消'] : null,
                yes: function () {
                    if (callback) {
                        callback();
                    }
                },
                btn2: function () {
                    layer.close(index);
                },
                success: function (layero, index) {

                }
            });
            if (!callback) {
                // layer.full(index);
            }
            return index;
        },


        /**初始化表格*/
        initTable: function (tableId, url, params, callback,pageList) {
            //封装分页对象 默认从第一条开始  每页10条
            var request = new Object();
            // 分页参数自定义
            $.openx.tableId = !tableId ? "#table" : "#" + tableId;
            // 定义表格的默认样式
            request.queryParams = function (data) {
                if (!params) {
                    return { "_openx_head": getOpenxHeader() }
                }
                var isExport = (!data.offset && !data.limit);
                var page = new Object();
                page.offset = data.offset;
                page.pageNum = isExport ? 1 : (parseInt(parseInt(data.offset) + parseInt(data.limit)) / parseInt(data.limit))
                page.pageSize = isExport ? 5000:data.limit;
                page.pageSizeZero = isExport;
                page.countSql = !isExport;
                page.isExport = isExport;
                params.page = page;
                params._openx_head = getOpenxHeader();
                return params;
            }

            //如果存在先销毁
            $($.openx.tableId).bootstrapTable('destroy');
            $($.openx.tableId).bootstrapTable({
                url: $.openx.url + url,
                queryParams: request.queryParams,
                pagination: true,
                align: "center",
                striped: true,
                pageNumber:$.openx.pageNumber,
                pageSize:$.openx.pageSize,
                search: false,
                showToggle: false,
                clickToSelect: true,
                pageList: pageList,
                method: 'post',
                showRefresh: true,
                silent: true,
                sidePagination: 'server',
                showColumns: !0,
                toolbar: "#TableToolbar",
                iconSize: "outline",
                icons: {
                    toggle: "glyphicon-list-alt",
                    columns: "glyphicon-list",
                    refresh: "glyphicon-refresh icon-refresh"

                },
                onPageChange: function (num, size) {
                    $.openx.pageNumber = num;
                    $.openx.pageSize =size;
                    $.openx.rows = [];
                },
                responseHandler: function (res) {
                    if (callback) {
                        callback(res);
                    }
                    return res;
                },
                onCheck: function (row) {
                    $.openx.rows.push(row);
                },
                onUncheck: function (row) {
                    for (var i = 0; i < $.openx.rows.length; i++) {
                        if ($.openx.rows[i] == row) {
                            $.openx.rows.splice(i, 1);
                        }
                    }
                },
                onCheckAll: function (rows) {
                    $.openx.rows = rows;
                },
                onUncheckAll: function (rows) {
                    $.openx.rows = [];
                }
            });

            $($.openx.tableId).on('click-row.bs.table', function (e, row, $element) {
                // 设置表格选择后的颜色
                $('.success').removeClass('success');
                $($element).addClass('success');
            });

            // 对应事件 onLoadSuccess
            $($.openx.tableId).on('load-success.bs.table', function (e, row, $element) {
                layer.closeAll('loading');
            });

            //对应事件 onLoadError
            $($.openx.tableId).on("load-error.bs.table", function (xhr, error) {

            	if (error === 500) {
            		layer.msg("数据加载失败,服务器出错");
            		layer.closeAll('loading');
                } else {
                    layer.msg("数据加载失败,服务器出错");
                }
            });
        },
        /**
         *  在进行更新操作后需要对表格进行刷新时可调用如下方法：$.openx.tableRefresh(nulll,null,true);
         * */
        tableRefresh: function (url, data, refresh) {
            if (url && data) $($.openx.tableId).bootstrapTable('refresh', { url: $.openx.url + url, query: data });
            if (refresh) $("button[name ='refresh'][type='button']").click();
            $.openx.rows = [];
        },


        /**
         *  请求后端时 可以收集表单数据为json格式 作为入参传递到后台  使用方式 $.openx.getJsonObj(''表单ID);
         * */
        getJsonObj: function (formId) {
            var obj = decodeURIComponent($('#' + formId).serialize().replace(/\+/g, " "));
            var str = "{";
            var paramsArr = obj.split('&'), temp, params;
            while (temp = paramsArr.pop()) {
                params = temp.split('=');
                str += "'" + params[0] + "':'" + params[1] + "',";
            }
            str = str.substr(0, str.length - 1)
            str += "}"
            console.log("表单对象内容：" + str)
            return eval('(' + str + ')');
        },
        /**得到表格中选中的行信息*/
        getSelectedRow: function () {
            return $.openx.rows;
        },
        innerHtml: function (id) {
            return document.getElementById(id).innerHTML;
        },
        setTableToolBar: function (id) {
            var toolbartpl = $.openx.innerHtml("toolbartpl");
            $('#' + id).html(toolbartpl);
        },
        /**点击删除按钮时调用，需手动调用*/
        onClickDelete: function (callback) {
            if ($.openx.rows.length <= 0) {
                layer.msg("请选择需要删除的数据", { time: 2000 });
                return false;
            } else {
                $.openx.confirm('确认要进行删除操作', function () {
                    return callback ? callback($.openx.getSelectedRow()) : false;
                })
            }
        },
        /**点击更新按钮时调用，需手动调用*/
        onClickUpdate: function (callback) {
            if ($.openx.rows.length != 1) {
                if ($.openx.rows.length == 0)
                    layer.msg("请选择需要更新的数据。", { time: 2000 });
                if ($.openx.rows.length > 1)
                    layer.msg("请选择一条数据进行更新。", { time: 2000 });
                return false;
            } else {
                return callback ? callback($.openx.getSelectedRow()) : false;
            }
        },
        /**取出数组中的某个元素 组合成新的数组*/
        getArrays: function (key, array) {
            var arr = [];
            if (array && array.length > 0) {
                for (var i = 0; i < array.length; i++) {
                    arr.push(array[i][key])
                }
            }
            return arr;
        },
        validation: function (formId) {
            var flag = true;
            var list = [];
            var form = $("#" + formId);

            var select = $(form).find("select[required='true']");
            var input = $(form).find("input[required='true']");
            if (select && select.length > 0) {
                list.push(select);
            }
            if (input && input.length > 0) {
                list.push(input);
            }

            for (var i = 0; i < list.length; i++) {
                list[i].each(function (index, item) {
                    if ($(item).val() === '') {
                        layer.tips($(item).attr("placeholder"), '#' + $(item).attr('id'), { tips: [2, '#78BA32'] });
                        $(item).focus();
                        flag = false;
                        return;
                    }
                })
            }
            return flag;
        },
        generatorId: function (value, row, index) {
            return index + 1;
        },
        formatDate: function (date, format) {
            var paddNum = function (num) {
                num += "";
                return num.replace(/^(\d)$/, "0$1");
            }
            //指定格式字符
            var cfg = {
                yyyy: date.getFullYear() //年 : 4位
                , yy: date.getFullYear().toString().substring(2)//年 : 2位
                , M: date.getMonth() + 1  //月 : 如果1位的时候不补0
                , MM: paddNum(date.getMonth() + 1) //月 : 如果1位的时候补0
                , d: date.getDate()   //日 : 如果1位的时候不补0
                , dd: paddNum(date.getDate())//日 : 如果1位的时候补0
                , hh: paddNum(date.getHours())  //时
                , mm: paddNum(date.getMinutes()) //分
                , ss: paddNum(date.getSeconds()) //秒
            }
            format || (format = "yyyy-MM-dd hh:mm:ss");
            return format.replace(/([a-z])(\1)*/ig, function (m) {
                return cfg[m];
            });
        },
        loadScript: function (urls) {
            /*var ver = "1.0";
            $X("/boss/web", "version").callx({
                onResult: function (result) {
                    ver = result.toString();
                    for (var index = 0; index < urls.length; index++) {
                        var script = document.createElement("script");
                        script.type = "text/javascript";
                        var url = urls[index];
                        var urlLength = url.trim().length;
                        var jsSuffixIndexStart = url.lastIndexOf(".js");
                        //以.js结尾
                        if(urlLength > 0 && jsSuffixIndexStart != -1 &&  jsSuffixIndexStart + 3 == urlLength){
                            url = url + "?v=" + ver;
                        }
                        script.src = url;
                        document.body.appendChild(script);
                    }
                },
                onError: function (error) {
                    console.log('后台服务没有启动');
                    for (var index = 0; index < urls.length; index++) {
                        var script = document.createElement("script");
                        script.type = "text/javascript";
                        var url = urls[index];
                        script.src = url;
                        document.body.appendChild(script);
                    }
                }
            });*/
            var  ver = new Date().getTime();
            for (var index = 0; index < urls.length; index++) {
                var script = document.createElement("script");
                script.type = "text/javascript";
                var url = urls[index];
                var urlLength = url.trim().length;
                var jsSuffixIndexStart = url.lastIndexOf(".js");
                //以.js结尾
                if(urlLength > 0 && jsSuffixIndexStart != -1 &&  jsSuffixIndexStart + 3 == urlLength){
                    url = url + "?v=" + ver;
                }
                script.src = url;
                document.body.appendChild(script);
            }
        },
		escapeHtml: function (string) {
            var entityMap = {
                "&": "&amp;",
                "<": "&lt;",
                ">": "&gt;",
                '"': '&quot;',
                "'": '&#39;',
                "/": '&#x2F;'
            };
            return String(string).replace(/[&<>"'\/]/g, function (s) {
                return entityMap[s];
            });
        }
    }
});


var getOpenxHeader = function () {
    var ls = window.localStorage;
    if (ls) {
        var v = ls.getItem("_openx_header");
        if (!v) {
            return null;
        }
        var openx_header = JSON.parse(v);
        if (openx_header) {
            return openx_header;
        }
        return null;
    }
}

if (param.auth_token) {
    $X().head('auth_token', param.auth_token);//auth_token
    $X().store('auth_token', param.auth_token);//auth_token
};

if (param.userCode) {
    $X().head('userCode', param.userCode);//userCode
    $X().store('userCode', param.userCode);//userCode
};

if (param.device) {
    $X().head('device', param.device);//device
    $X().store('device', param.device);//device
};


//对请求进行加载处理
$.ajaxSetup({
    beforeSend: function () {
        layer.load();
    },
    complete: function (xhr, status) {
        layer.closeAll('loading')
        if (xhr && xhr.status === 500) {
            var errorJSON = xhr.responseJSON || null;
            if (errorJSON && (errorJSON.code === '70009999' || (errorJSON.code && errorJSON.code.startsWith("020000")))) {
                $.openx.confirm("您还未进行登录，是否去登录？", function () {
                    layer.closeAll();
                    top.location.href = ecp_boss_authUrl;
                })
            } else {
                layer.msg(errorJSON.message ? errorJSON.message : "系统错误，请联系管理员", { time: 3000, icon: 5 });
            }
        }
    },
    error: function () {
        layer.closeAll('loading')
    }
});
